package oboe.controllers;
import haxe.remoting.Context;
import haxe.remoting.HttpConnection;
import oboe.core.Oboe;
import oboe.core.SigSlot;

/**
 * ...
 * @author Felipe Manga
 */

class Server extends SigSlot
{
	private var clientMsgs:Array<Dynamic>;
	
	public function new() 
	{
		super();
		this.clientMsgs = [];
	}
	
	@slot override function onAddToParent():Void
	{
		super.onAddToParent();
		var ctx = new Context();
		ctx.addObject( "server", { message: extMessage } );
		if ( !HttpConnection.handleRequest( ctx ) )
		{
			this.shortSignal("onNonRemotingRequest", []);
		}
	}
	
	function extMessage( name:String, args:Array<Dynamic> )
	{
		this.shortSignal( "onRemotingRequest", [] );
		
		var ret:Array<Bool> = [true];
		var autoPoll:Bool = args.pop();
		this.shortSignal( "checkPermit", [ name, args, ret] );
		if ( ret[0] ) this.shortSignal( name, args );
		else this.onClientMessage("permissionDenied", [ name, args ]);
		if ( autoPoll && name != "onPoll" )
		{
			ret[0] = true;
			this.shortSignal( "checkPermit", ["onPoll", [], ret]  );
			if( ret[0] ) Oboe.global.signalDown("onPoll", []);
		}
		Oboe.global.signalDown("onShutdown", []);
		return clientMsgs;
	}
	
	@slot function onClientMessage( name:String, args:Array<Dynamic> )
	{
		this.clientMsgs.push( { name:name, args:args } );
	}
	
}